using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using OziExplorer.Api;
using OziExplorer.Api.Tools;

namespace OziMonitoring
{
	class OziHelper
	{
		/// <summary>
		/// Convert Color to RGB
		/// </summary>
		/// <param name="color"></param>
		/// <returns></returns>
		public static int ToOziColor(Color color)
		{
			return color.R | color.G << 8 | color.B << 16;
		}

		/// <summary>
		/// Add new point in Ozi
		/// </summary>
		/// <param name="row"></param>
		public static void AddNewPoint(OziPointsInformation.tblPointsRow row)
		{
			// check point already present
			int pointNumber = OziApi.GetWPNumberFromName(row.Name);
			if (pointNumber > 0)
				UpdatePoint(row);
			else
			{
				double lat = row.Latitude;
				double lon = row.Longitude;
				//OziApi.ConvertDatum("WGS 84", OziApi.MapDatum, ref lat, ref lon);
				OziApi.CreateWP(row.Name, 1, lat, lon, -777,
				                OziDateTools.FromDateTime(DateTime.Now),
				                (int)OziMapDisplayFormat.NameWithDot,
				                (int)OziPointerDirection.Bottom,
				                0,
				                OziHelper.ToOziColor(Color.Red),
				                OziHelper.ToOziColor(Color.Yellow), 0,
				                row.Description, 10, 0, 17);
				Debug.WriteLine(string.Format("Added new point: {0}, {1}", row.Latitude.ToString(), row.Longitude.ToString()));
			}
		}

		/// <summary>
		/// Update point in Ozi
		/// </summary>
		/// <param name="row"></param>
		public static void UpdatePoint(OziPointsInformation.tblPointsRow row)
		{
			//int pointNu7mber = OziApi.GetWPNumberFromName("13123");
			int pointNumber = OziApi.GetWPNumberFromName(row.Name);
			if (pointNumber > 0)
			{
				double lat = row.Latitude;
				double lon = row.Longitude;
				OziApi.ConvertDatum("WGS 84", OziApi.MapDatum, ref lat, ref lon);
				OziApi.RepositionWP(pointNumber, lat, lon);
				Debug.WriteLine(string.Format("Point moved: {0}, {1}", lat.ToString(), lon.ToString()));
			}
		}

		/// <summary>
		/// Delete point in Ozi
		/// </summary>
		/// <param name="row"></param>
		public static void DeletePoint(OziPointsInformation.tblPointsRow row)
		{
			OziApi.DeleteWPByName(row.Name);
		}

		/// <summary>
		/// Get Ozi path
		/// </summary>
		/// <returns></returns>
		public static string GetOziPath()
		{
			// use settings to get Ozi Path
			MainSettings mainSettings = new MainSettings();
			string oziPath = mainSettings.OziPath;
			if (System.IO.File.Exists(oziPath))
				return oziPath;
#if DEBUG
			// Get local file path for testing
			oziPath = @"D:\Program Files\OziExplorer\OziExp.exe";
			if (System.IO.File.Exists(oziPath))
				return oziPath;
			// Get local file path for testing
			oziPath = @"C:\Program Files\OziExplorer\OziExp.exe";
			if (System.IO.File.Exists(oziPath))
				return oziPath;
#endif
			return String.Empty;
		}
	}
}
